<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type {
  DnsResolveDomainListItem,
  GtmInstanceItem,
} from '@/apis/model/dns'
import { Message } from '@arco-design/web-vue'
import { omit } from 'lodash-es'
import {
  addDnsAuthorityGtmInstanceApi,
  getDnsAuthorityDomainsApi,
  getDnsAuthorityGtmInstanceApi,
  updateDnsAuthorityGtmInstanceApi,
} from '@/apis/modules/dns'
import { poolTypeOptions, ttlOptions } from '@/constants/dns'

interface IProps {
  record: GtmInstanceItem
}
const props = defineProps<IProps>()
const emit = defineEmits(['reload'])
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const formState = reactive({
  name: '',
  ttl: 30,
  app_id: undefined,
  address_pool_type: 1,
  record_name: '',
  domain_name: '',
})
const title = computed(() => (props.record?.id ? '编辑实例' : '新建实例'))
const appList = computed<OptionItem[]>(() => useAppStore().appList || [])
const rules: Record<string, FieldRule> = {
  name: {
    required: true,
    validator(value, callback) {
      if (!value) {
        return callback('实例名称不能为空')
      }
      callback()
    },
  },
  app_id: { required: true, message: '所属应用不能为空' },
  record_name: { required: true, message: '主机记录不能为空' },
  domain_name: { required: true, message: '域名不能为空' },
  ttl: { required: true, message: '请选择TTL' },
}
function handleJump() {
  window.open('/dns/domain-analysis?type=open', '_target')
}
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return false
  const apiPath = props.record?.id
    ? updateDnsAuthorityGtmInstanceApi
    : addDnsAuthorityGtmInstanceApi
  return apiPath(formState).then(() => {
    Message.success('操作成功')
  })
}
async function getDetail() {
  await getDnsAuthorityGtmInstanceApi({ id: props.record?.id }).then(
    (res: any) => {
      Object.assign(formState, {
        ...omit(res, ['created_at', 'updated_at', 'strategy_count']),
      })
    },
  )
}
const domainList = ref<DnsResolveDomainListItem[]>([])
const { loading, run } = useListRequest(getDnsAuthorityDomainsApi, {
  afterFn(res: DnsResolveDomainListItem[]) {
    domainList.value = res.map(item => ({
      value: item.id,
      label: item.name,
    }))
  },
  params: { limit: 0, offset: 0, order: 'desc', sort: 'created_at' },
})
function handleOpen() {
  if (props.record?.id)
    getDetail()
  run()
}
function handleClose() {
  formRef.value?.resetFields()
  emit('reload')
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :title="title"
    :width="480"
    :mask-closable="false"
    :before-open="handleOpen"
    :before-ok="handleSubmit"
    :before-close="handleClose"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
    >
      <a-form-item
        label="实例名称"
        field="name"
        asterisk-position="end"
      >
        <a-input
          v-model="formState.name"
          :max-length="32"
          show-word-limit
          placeholder="请输入实例名称"
        />
      </a-form-item>
      <a-form-item
        label="所属应用"
        field="app_id"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.app_id"
          :options="appList"
          :disabled="!!record?.id"
          placeholder="请选择所属应用"
        />
      </a-form-item>
      <a-form-item
        field="address_pool_type"
        hide-asterisk
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            地址池来源
            <span class="text-4 text-[#FA5566]">*</span>
            <a-tooltip
              :show-arrow="false"
              position="top"
              content-class="w-[264px] !text-xs/5"
            >
              <i-icons-question
                class="question-icon cursor-pointer !text-[#86909c]"
              />
              <template #content>
                <div>静态地址池：手动管理地址。</div>
                <div>CDN 动态地址池：由 CDN 服务自动同步。</div>
              </template>
            </a-tooltip>
          </div>
        </template>
        <a-radio-group
          v-model="formState.address_pool_type"
          size="small"
          :disabled="!!record?.id"
          :options="poolTypeOptions"
        />
      </a-form-item>
      <a-form-item
        field=""
        hide-asterisk
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            接入域名
            <span class="text-4 text-[#FA5566]">*</span>
          </div>
        </template>
        <div class="w-full flex items-start">
          <a-form-item
            label=""
            field="record_name"
            hide-asterisk
            class="w-full mb-0!"
          >
            <a-input
              v-model="formState.record_name"
              :max-length="190"
              :disabled="!!record?.id"
              class="w-full"
              placeholder="请输入主机记录"
            />
          </a-form-item>
          <div class="h-[40px] w-4 flex items-end justify-center">
            .
          </div>
          <a-form-item
            label=""
            field="domain_name"
            hide-asterisk
            class="w-full mb-0!"
          >
            <a-select
              v-model="formState.domain_name"
              :loading="loading"
              :disabled="!!record?.id"
              :show-footer-on-empty="true"
              placeholder="请选择域名"
            >
              <a-option
                v-for="item in domainList"
                :key="item.value"
                :value="item.label"
              >
                {{ item.label }}
              </a-option>
              <template #footer>
                <div
                  class="h-8 flex cursor-pointer items-center gap-x-1 px-3 text-[#00A65B] leading-8"
                  @click="handleJump"
                >
                  <span class="text-xs leading-[19px]">新建域名</span>
                  <i-icons-jump size="14px" />
                </div>
              </template>
            </a-select>
            <i-icons-refresh
              class="ml-2 cursor-pointer"
              :class="{ 'animate-spin': loading }"
              @click="run"
            />
          </a-form-item>
        </div>
      </a-form-item>
      <a-form-item
        label="TTL"
        field="ttl"
        asterisk-position="end"
      >
        <a-select
          v-model="formState.ttl"
          placeholder="请选择TTL"
          :options="ttlOptions"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style lang="less" scoped>
.question-icon {
  color: #86909c;
  width: 14px !important;
  height: 14px !important;
  cursor: pointer;

  &:hover {
    color: #00a65b;
  }
}
</style>
